package com.sskj.xgja.transaction;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.sskj.base.BuildConfig;
import com.sskj.base.data.User;
import com.sskj.base.simple.SimpleTextWatcher;
import com.sskj.base.socket.MarketWebSocket;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.GsonUtil;
import com.sskj.base.utils.MoneyValueFilter;
import com.sskj.base.utils.NumberUtil;
import com.sskj.base.utils.WebSocketObserver;
import com.sskj.xgja.Constant;
import com.sskj.xgja.MVPFragment;
import com.sskj.xgja.MyApplication;
import com.sskj.xgja.R;
import com.sskj.xgja.login.LoginActivity;
import com.sskj.xgja.market.MarketSearchListActivity;
import com.sskj.xgja.market.bean.MarketData;
import com.sskj.xgja.market.bean.SocketMarket;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;
import okhttp3.WebSocket;

/**
 * @author Hey
 * Create at  2019/03/20
 */
public class BuyInFragment extends MVPFragment<BuyInPresenter> {

    @BindView(R.id.spinner_type)
    TextView spinnerType;
    @BindView(R.id.et_price)
    TextView etPrice;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.tv_subtract)
    TextView tvSubtract;
    @BindView(R.id.tv_amount)
    EditText tvAmount;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.lever)
    TextView level;
    @BindView(R.id.tv_newest_price)
    TextView tvNewPrice;
    @BindView(R.id.tv_deal_money)
    TextView totalMoney;
    @BindView(R.id.tv_fee)
    TextView tvFee;
    private TextView priceText;
    @BindView(R.id.btn_sell_out)
    Button btnSellOut;

    @BindView(R.id.edit_coin_name)
    EditText editCoinName;

    @BindView(R.id.market_search)
    ImageView marketSearch;


    private BottomSheetDialog bottomSheetDialog;
    private TextView tv_market_price;
    private TextView tv_limited_price;
    private TextView tv_cancel;

    private double amount = 1;
    private User user;

    private String stockCode;
    private String stockName;

    private double fee;
    private double price = 0;
    private double totalPrice = 0;
    private double stopLoss;
    private double stopProfit;
    private int tradeType = Constant.BUY;

    private MarketWebSocket webSocket;

    private MarketData currentData;

    private double rate;

    private boolean getDetail;
    private WebSocketObserver webSocketObserver;
    private String preCode;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getArguments() == null) {
            throw new RuntimeException("请传入买卖类型");
        }
        tradeType = getArguments().getInt("type");
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_buy_in;
    }

    @Override
    public BuyInPresenter getPresenter() {
        return new BuyInPresenter();
    }

    @Override
    public void initView() {
        etPrice.setHint(tradeType == Constant.BUY ? "以市场上最优价融资" : "以市场上最优价融券");
        changeTradeType();
        RxBus.getDefault().register(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter != null) {
            mPresenter.getAccountDetail();
        }
        if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
            if (tradeType == Constant.BUY) {
                btnSellOut.setText("融资(做多)");
                btnSellOut.setBackgroundResource(R.drawable.btn_red_bg);
            } else {
                btnSellOut.setText("融券(做空)");
                btnSellOut.setBackgroundResource(R.drawable.btn_green_bg);
            }
        } else {
            btnSellOut.setText("登录");
        }
        ClickUtil.click(marketSearch, view -> {
            if (TextUtils.isEmpty(getText(editCoinName))) {
                ToastUtils.show("请输入股票名称或代码");
                return;
            }
            MarketSearchListActivity.start(getContext(), false, tradeType == Constant.BUY ? 0 : 1, getText(editCoinName));
        });
    }


    @Override
    public void initData() {
        mPresenter.getAccountDetail();
        tvAmount.setText(NumberUtil.keep0(String.valueOf(amount)));
        tvAmount.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    Double num = Double.parseDouble(s.toString());
                    if (num < 1) {
                        ToastUtils.show("数量不能小于1");
                        tvAmount.setText("1");
                        tvAmount.setSelection(tvAmount.getText().length());
                    }
                    amount = Double.parseDouble(s.toString());
                    if (currentData != null) {
                        setMoney(currentData);
                    }

                } else {
                    amount = 0;
                }
            }
        });
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter(4)});
    }

    private void initWebSocket() {
        if (webSocketObserver == null) {


            JSONObject message = new JSONObject();
            try {
                message.put("sub", "stock@" + currentData.getCode());
//            webSocket = new MarketWebSocket(BuildConfig.MarketWS, "buy", message.toString());
//            webSocket.observer("buy", new WebSocketObserver() {
//                @Override
//                public void onNext(String s) {
//                    SocketMarket data = GsonUtil.GsonToBean(s, SocketMarket.class);
//                    webSocketUpdate(data);
//                }
//            });
                webSocketObserver = new WebSocketObserver(com.sskj.base.Constant.MARKET_WS) {

                    @Override
                    public void onOpen(WebSocket webSocket, Response response, String type) {
                        webSocket.send(message.toString());
                    }
                };
                webSocketObserver
                        .map(s -> new Gson().fromJson(s, SocketMarket.class))
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(data -> webSocketUpdate(data), e -> {

                        });
                preCode = currentData.getCode();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            webSocketObserver.send("{\"unsub\":\"stock@" + preCode + "\"}");
            webSocketObserver.send("{\"sub\":\"stock@" + currentData.getCode() + "\"}");
            preCode = currentData.getCode();
        }
    }

    private void webSocketUpdate(SocketMarket data) {
        if (data == null || currentData == null) {
            return;
        }
        if (data.getCode().equals(currentData.getCode())) {
            if (priceText != null) {
                priceText.setText(String.valueOf(data.getPrice()));
            }
            currentData.setPrice(String.valueOf(data.getPrice()));
            setMoney(currentData);
            setText(tvNewPrice, data.getPrice() + "");
            tvNewPrice.setTextColor(getResources().getColor(data.getChange() > 0 ? R.color.red : R.color.green));
        }
    }


    @Override
    public void initListener() {
        ClickUtil.click(200, tvAdd, view -> {
            amount++;
            tvAmount.clearFocus();
            tvAmount.setText(NumberUtil.keep0(String.valueOf(amount)));
        });
        ClickUtil.click(200, tvSubtract, view -> {
            tvAmount.clearFocus();
            if (amount > 1) {
                amount--;
                tvAmount.setText(NumberUtil.keep0(String.valueOf(amount)));
            }
        });
        ClickUtil.click(btnSellOut, view -> {
            if (TextUtils.isEmpty(MyApplication.getAccount()) || TextUtils.isEmpty(MyApplication.getToken())) {
                LoginActivity.start(getContext());
                return;
            }
            if (getText(tvNewPrice).equals("--")) {
                ToastUtils.show("请选择股票");
                return;
            }
            price = Double.parseDouble(getText(tvNewPrice));  //最新价格
            if (isEmpty(tvAmount)) {  // 手数
                ToastUtils.show("请输入数量");
                return;
            }

            View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_place_order, null);
            TextView name = dialogView.findViewById(R.id.name);
            TextView code = dialogView.findViewById(R.id.code);
            priceText = dialogView.findViewById(R.id.price);
            TextView amount = dialogView.findViewById(R.id.amount);
            TextView orientation = dialogView.findViewById(R.id.orientation);
            TextView cancel = dialogView.findViewById(R.id.cancel);
            TextView confirm = dialogView.findViewById(R.id.confirm);
            setText(name, currentData.getName());
            setText(priceText, currentData.getPrice());
            setText(code, currentData.getCode());
            setText(amount, getText(tvAmount));
            setText(orientation, tradeType == Constant.BUY ? "融资" : "融券");
            orientation.setTextColor(getResources().getColor(tradeType == Constant.BUY ? R.color.text_e83 : R.color.color_03c087));
            AlertDialog dialog = new AlertDialog.Builder(getContext())
                    .setView(dialogView)
                    .show();
            cancel.setOnClickListener(v -> dialog.dismiss());
            confirm.setOnClickListener(v -> {
                dialog.dismiss();
                mPresenter.placeOrder(tradeType == Constant.BUY ? "1" : "2", getText(tvAmount), currentData.getCode(), "", "");
            });
        });

    }

    public void changeTradeType() {
        if (tradeType == Constant.BUY) {
            btnSellOut.setText("融资(做多)");
            btnSellOut.setBackgroundResource(R.drawable.btn_red_bg);
        } else {
            btnSellOut.setText("融券(做空)");
            btnSellOut.setBackgroundResource(R.drawable.btn_green_bg);
        }
    }


    public static BuyInFragment newInstance(int type) {
        BuyInFragment fragment = new BuyInFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setCoin(MarketData coin) {
        currentData = coin;
        if (coin != null) {
            mPresenter.getMarketDetail(coin.getCode(), true);
            initWebSocket();
        }
    }


    public void placeOrderSuccess() {
        ToastUtils.show("下单成功");
        if (getParentFragment() != null) {
            TransactionHomeFragment fragment = (TransactionHomeFragment) getParentFragment();
            fragment.getPresenter().getAccountDetail(getAccount(), true);
        }
        tvAmount.setText("1");
        mPresenter.getAccountDetail();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webSocketObserver != null) {
            webSocketObserver.close();
        }
        RxBus.getDefault().unregister(this);
    }

    public void setMarketDetail(MarketData data) {
        currentData = data;
        if (data != null) {
            setMoney(currentData);
            spinnerType.setText(data.getName() + "/" + data.getCode());
            tvNewPrice.setText(TextUtils.isEmpty(data.getPrice()) ? "--" : data.getPrice());
        }
    }

    // 設置 保證金
    public void setMoney(MarketData data) {
        // 融資保證金 = （最新价*手数*股数）*融资保证金比例
        if (TextUtils.isEmpty(getText(tvAmount)) || data == null || data.getShares() == null) {
            return;
        }
        BigDecimal divide = new BigDecimal(data.getPrice()).multiply(new BigDecimal(data.getShares()))
                .multiply(new BigDecimal(getText(tvAmount)))
                .multiply(new BigDecimal(tradeType == Constant.BUY ? data.getLeverage_rz() : data.getLeverage_rj()));
        String money = divide.toString();
        editMoney.setText(NumberUtil.keepDown(money, 2));
        level.setText((tradeType == Constant.BUY ? data.getLeverage_rz() : data.getLeverage_rj()) + "倍杠杆");

        // 融资融券手续费 = 最新价*手数*股数）*手续费比例
        BigDecimal divideFee = new BigDecimal(data.getPrice()).multiply(new BigDecimal(data.getShares()))
                .multiply(new BigDecimal(getText(tvAmount)))
                .multiply(new BigDecimal(data.getTrans_fee()))
                .divide(new BigDecimal(100));
        String transFee = divideFee.toString();
        totalMoney.setText(NumberUtil.keepDown(transFee, 2));
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUi(SocketMarket data) {
        if (currentData != null) {
            if (data.getCode().equals(currentData.getCode())) {
                setMoney(currentData);
                tvNewPrice.setText(TextUtils.isEmpty(String.valueOf(data.getPrice())) ? "--" : String.valueOf(data.getPrice()));
                tvNewPrice.setTextColor(getResources().getColor(data.getChange() > 0 ? R.color.red : R.color.green));
            }
        }
    }

    public void setAccountInfo(User data) {
        tvFee.setText(data.getWallone());

    }
}
